<?php

namespace App\Http\Controllers\Api;

use App\Level;
use App\Socialite;
use App\Upgrade;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class UpgradeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * @param Request $request
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|string|\Symfony\Component\HttpFoundation\Response
     */
    public function store(Request $request)
    {
        if (!$request->level_id || !$level = Level::find($request->level_id)) {
            return response(['message' => '请选择升级会员'], 400);
        }
        if ($request->level_id <= Auth::user()->level_id) {
            return response(['message' => '请选择高等级的会员'], 400);
        }
        $upgrade = Upgrade::create([
            'user_id' => Auth::id(),
            'amount' => $level->condition,
            'order_sn' => $this->generateOrderSn(),
            'status' => 0,
            'level_id' => $request->level_id
        ]);

        $payment = Factory::payment(config('wechat.payment.default'));
        $openid = Socialite::where('user_id', Auth::id())->where('driver', 'wechat')->value('open_id');
        if (!$openid) {
            return response(['尚未绑定微信'], 401);
        }
        $attribute = [
            'body'         => '天南山文化',
            'detail'       => '天南山文化会员升级',
            'out_trade_no' => $upgrade->order_sn,
            'total_fee'    => $upgrade->amount * 100,
            'notify_url'   => url('/api/notify/upgrade', ['wxpay'.'-'.$upgrade->id]),
            'trade_type'   => 'JSAPI',
            'openid'       => $openid,
        ];
        $result = $payment->order->unify($attribute);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            return $payment->jssdk->bridgeConfig($result['prepay_id']);
        }
        return response(['message' => '支付信息核对中,请稍后查看支付结果'], 400);
    }

    /**
     * 生成订单编号
     * @return null|string
     */
    protected function generateOrderSn() {
        $orderSn = null;
        // 保证不会有重复订单号存在
        while(true){
            $orderSn = date('YmdHis').rand(1000,9999); // 订单编号
            $sn = Upgrade::where("order_sn", $orderSn)->first();
            if(!$sn)
                break;
        }
        return $orderSn;
    }


    /**
     * Display the specified resource.
     *
     * @param  \App\Upgrade  $upgrade
     * @return \Illuminate\Http\Response
     */
    public function show(Upgrade $upgrade)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Upgrade  $upgrade
     * @return \Illuminate\Http\Response
     */
    public function edit(Upgrade $upgrade)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Upgrade  $upgrade
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Upgrade $upgrade)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Upgrade  $upgrade
     * @return \Illuminate\Http\Response
     */
    public function destroy(Upgrade $upgrade)
    {
        //
    }
}
